<?php
//decode by http://奥森世纪/
namespace app\home\controller;

use app\home\model\Recharge as UserRecharge;
use think\Db;
use think\Log;
use think\Cache;

class Recharge extends Base
{
    public function index(){
        $member = $this->checkLogin();
        return $this->fetch(__FUNCTION__,[
        	'member'=>$member
        	]);
    }
    
     public function index2(){
        $member = $this->checkLogin();
        return $this->fetch(__FUNCTION__);
    }

    public function post() {
        $member = $this->checkLogin();

        $params = request()->post();
        $result = $this->validate($params,'Recharge');
        if($result !== true){
            message($result,'','error');
        }

        //处理是整数的
        //params_floor(['credit2'], $params);

        if($params['credit2'] < 20){
            message('充值金额不能少于20元','','error');
        }

        $params['thumbs'] = '';
        $ordertt = "TD".time();
        Db::startTrans();
        $status3 = UserRecharge::addInfo([
            'uid' => $member['uid'],
            'username' => $member['username'],
            'credit2' => $params['credit2'],
            'realname' => '',
            'account' => $ordertt,
            'pay_time' => '',
            'thumbs' => $params['thumbs'],
            'create_time' => TIMESTAMP
        ]);
        if(!$status3){
            Db::rollback();
            message('充值失败：-3','','error');
        }

        $payparams = array(
                    'subject' => '充值-' . $params['credit2'],
                    'out_trade_no' => $status3,
                    'total_amount' => $params['credit2'],
                    'domain' => $this->get_domain()
                );

        if ($params['pay_type'] == 1) {
            $payparams['goods_tag'] = '';
            $payparams['notify_url'] = $this->get_domain() . 'home/wxnotify/index.html';
            $payparams['wap_url'] = $this->get_domain() . '/home/account.html';
            $payparams['wap_name'] = '充值-' . $params['credit2'];

           // $h5pay = new \wxpay\H5pay();
          //  $result = $h5pay->pay($payparams);

            Db::commit();

                $codepay_id="454385";//码支付ID
                $codepay_key="PnPnpNjtOPHm1gUo0yh8iD0cOlJwjqvF"; //密钥
                $paytype=$params['type'];
                $data = array(
                    "id" => $codepay_id,//你的码支付ID
                    "pay_id" => $ordertt, //唯一标识 可以是用户ID,用户名,session_id(),订单ID,ip 付款后返回 sucaihuo.com
                    "type" => $paytype,//1支付宝支付 3微信支付 2QQ钱包
                    "price" => $params['credit2'],//金额100元
                    "param" => $member['uid'],//自定义参数
                    "notify_url"=>"https://wap.Wacp.top/home/notify/mazhifunotify",//通知地址
                    "return_url"=>"https://wap.Wacp.top/home/account",//跳转地址

                ); //构造需要传递的参数

                ksort($data); //重新排序$data数组
                reset($data); //内部指针指向数组中的第一个元素

                $sign = ''; //初始化需要签名的字符为空
                $urls = ''; //初始化URL参数为空

                foreach ($data AS $key => $val) { //遍历需要传递的参数
                    if ($val == ''||$key == 'sign') continue; //跳过这些不参数签名
                    if ($sign != '') { //后面追加&拼接URL
                        $sign .= "&";
                        $urls .= "&";
                    }
                    $sign .= "$key=$val"; //拼接为url参数形式
                    $urls .= "$key=" . urlencode($val); //拼接为url参数形式并URL编码参数值

                }
                $query = $urls . '&sign=' . md5($sign .$codepay_key); //创建订单所需的参数
                $url = "http://api2.fateqq.com:52888/creat_order/?{$query}"; //支付页面

                header("Location:{$url}"); //跳转到支付页面
           // $this->redirect($result["mweb_url"] . "&redirect_url=" . urlencode($payparams['wap_url']));

        } elseif ($params['pay_type'] == 2) {
            $wappay = new \alipay\Wappay();
            $result = $wappay->pay($payparams);
            echo $result;

            Db::commit();
        } else {
            message('充值失败','','error');
        }
    }
    public function preRecharge() {
        $member = $this->checkLogin();
        $begin = strtotime(date('Y-m-d')); 
        $end = strtotime(date('Y-m-d'))+24*3600;
        $jinricishu = db('recharge')->where('uid',$member['uid'])->where('status',0)->where('create_time','>',$begin)->where('create_time','<',$end)->where('jilu',date('Ymd'))->count();
        if($jinricishu>=3){
            to_json($code = 0,$message = '今日未完成订单过多',$data =[]);die;
        }
        $params = request()->post();
        $order_no=$this->create_order_no();
        $status3 = UserRecharge::addInfo([
            'uid' => $member['uid'],
            'username' => $member['username'],
            'credit2' => $params['credit2'],
            'realname' => '',
            'account' => $order_no,
            'pay_method'=>$params['type']==1?2:1,
            'pay_time' => '',
            'thumbs' => '',
            'create_time' => TIMESTAMP,
            'jilu'=>date('Ymd')
        ]);
        if($status3){
            $zhifu = db('zhifu')->find();
            $erweima = $zhifu['weixin'];
            if($params['type']==1){
                $erweima = $zhifu['zhifubao'];
            }
            $return_data=array(
                        'order_no'=>$order_no,
                        'erweima' =>'/uploads/'.$erweima,
                        'uid'=>$member['uid']
                      );
            to_json($code = 1,$message = '提交成功',$data =$return_data);

        }else{

            to_json($code = 0,$message = '提交失败',$data =[]);
        }
    }
    //充值提交
    public function cztj() {
        $member = $this->checkLogin();
        $data1['update_time'] = time();
        $data1['yanzheng'] = $member['uid'];
        $params = request()->post();
        $rst=db('recharge')->where('account',$params['order_no'])->update($data1);
        if($rst){
            to_json($code = 1,$message = '提交成功,请等待客服充值',$data =[]);
        }else{
            to_json($code = 0,$message = '提交失败',$data =[]);
        }
    }
    
    




    public function preRecharge_old() {
        $member = $this->checkLogin();
        $params = request()->post();
        $result = $this->validate($params,'Recharge');
        if($result !== true){
        	 to_json($code = 0,$message = $result,$data =[]);
            //message($result,'','error');
        }
        //处理是整数的
        //params_floor(['credit2'], $params);

        if($params['credit2'] < 20){
        	//	to_json($code = 0,$message = '充值金额不能少于20元',$data =[]);
            // message('充值金额不能少于30元','','error');
        }
        $order_no=$this->create_order_no();
        $status3 = UserRecharge::addInfo([
            'uid' => $member['uid'],
            'username' => $member['username'],
            'credit2' => $params['credit2'],
            'realname' => '',
            'account' => $order_no,
            'pay_method'=>$params['type']==1?2:1,
            'pay_time' => '',
            'thumbs' => '',
            'create_time' => TIMESTAMP
        ]);


        $data=array(
                        'money'=>$params['credit2'],
                        'type'=>$params['type'],
                        'status'=>1,
                        'uid' => $member['uid'],
                        'username' => $member['username'],
                        'order_no'=>$order_no,
                        'add_time'=>time(),
                    );
        $rst=db('order')->insert($data);

        if($rst){
            $return_data=array(
                        'order_no'=>$data['order_no'],
                      );
            to_json($code = 1,$message = '提交成功',$data =$return_data);

        }else{

            to_json($code = 0,$message = '提交失败',$data =[]);
        }
    }
    
    
    public function order_query(){

                 $params = request()->param();
                 if(!$params['order_no']){
                    to_json($code = 0,$message = '缺少参数',$data =[]);
                 }
                $order_no=$out_trade_no=$params['order_no'];
                 $order_model=db('order');
                 $order_info=$order_model->where('order_no',$order_no)->find();
                    if(!$order_info){
                    to_json($code = 0,$message = '请求错误',$data =[]);
                 }

                   if($order_info['status'] == 2){
                    to_json($code = 3,$message = '已支付',$data =[]);
                 }

$is_cache=Cache::get($order_no);

if($is_cache){
	 to_json($code = 0,$message = '正在查询中',$data =[]);
}

Cache::set($order_no,1,600);


                 $rst=[];
                 if($order_info['type'] == 2){
                        $rst=$this->ali_order_query($order_no,$order_info);
                 }

                   if($order_info['type'] == 1){
                        $rst=$this->wx_order_query($order_no,$order_info);
                 }

    }
    
    
    private function ali_order_query($order_no='',$order_info=''){


Db::startTrans();

            $order_model=db('order');
            $out_trade_no=$order_no;

        require_once 'plugins/alipay/f2fpay/service/AlipayTradeService.php';

            //第三方应用授权令牌,商户授权系统商开发模式下使用
        $appAuthToken = "";//根据真实值填写

        //构造查询业务请求参数对象
        $queryContentBuilder = new \AlipayTradeQueryContentBuilder();
        $queryContentBuilder->setOutTradeNo($out_trade_no);

        $queryContentBuilder->setAppAuthToken($appAuthToken);

        //初始化类对象，调用queryTradeResult方法获取查询应答
        $queryResponse = new \AlipayTradeService($config);
        $queryResult = $queryResponse->queryTradeResult($queryContentBuilder);

                    $result=$queryResult->getResponse();
                    $alipay_rst=$this->object_array($result);

                     file_put_contents("123.txt",json_encode($alipay_rst));
                     Cache::set($order_no,'');
                switch ($queryResult->getTradeStatus()){
                    case "SUCCESS":
                     /*   echo "支付宝查询交易成功:"."<br>--------------------------<br>";
                        print_r($queryResult->getResponse());*/
                        $amount=$alipay_rst['total_amount'];
                        if($amount !=$order_info['money']){
                                to_json($code = 0,$message = '支付金额错误',$data =[]);
                        }

                    $update['status'] = 1;
                    $update['note'] = $alipay_rst['trade_no'];
                    $update['pay_time'] = date('Y-m-d H:i:s', time());
                    $update['update_time'] = time();
                    $res1 = Db::name("recharge")->where("account = ".$order_info['order_no'])->update($update);
                    $Member_che = Db::name("member")->where("uid =" .$order_info['uid'])->find();

                    $ying['credit2'] = $Member_che['credit2']+$amount;
                   file_put_contents('11.txt',json_encode($ying));
                    $ying_che = Db::name("member")->where("uid =" . $order_info['uid'])->update($ying);
                      
                      $status2['uid'] =$order_info['uid'];
                      $status2['type'] ='credit2';
                      $status2['num'] =$amount;
                      $status2['title'] ='会员充值';
                      $status2['remark'] ="充值金额：{$amount}。";
                      $status2['create_time'] =time();
					  $status2['balance']=$ying['credit2'];

                      file_put_contents('2222.txt',json_encode($status2));
                    $ass = Db::name("credit_record")->insert($status2);
	

                    $order_data=[
                        'status'=>2,
                        'trade_no'=>$alipay_rst['trade_no'],
                        'buyer_logon_id'=>$alipay_rst['buyer_logon_id'],
                        'send_pay_date'=>$alipay_rst['send_pay_date'],
                        'query_time'=>time(),
                    ];
                    $rst=$order_model->where('order_no',$order_no)->update($order_data);
                    if($rst && $ass && $ying_che){
                    	Db::commit();
                    	
                         to_json($code = 1,$message = '支付宝支付成功',$data =[]);
                    }else{
                    	 Db::rollback();
                          to_json($code = 0,$message = '更新用户信息失败，请联系客服',$data =[]);
                    }
                        break;
                    case "FAILED":
                        //echo "支付宝查询交易失败或者交易已关闭!!!"."<br>--------------------------<br>";

                      to_json($code = 0,$message = '交易失败',$data =[]);
                 //           print_r($queryResult->getResponse());

                        break;
                    case "UNKNOWN":
            //            echo "系统异常，订单状态未知!!!"."<br>--------------------------<br>";
                      to_json($code = 0,$message = '系统错误',$data =[]);
                //      return ['code'=>0,'msg'=>'查询错误'];

                   //         print_r($queryResult->getResponse());

                        break;
                    default:
                      to_json($code = 0,$message = '查询失败',$data =[]);
                    //  return ['code'=>0,'msg'=>'查询失败'];
                    //    echo "不支持的查询状态，交易返回异常!!!";
                        break;
                }

    }

    private function wx_order_query($order_no='',$order_info=''){

                require_once "plugins/weixin/lib/WxPay.Api.php";
                require_once "plugins/weixin/example/WxPay.MicroPay.php";
                require_once "plugins/weixin/example/WxPay.Config.php";
                //订单号
                $config = new \WxPayConfig();
                    $out_trade_no =$order_no;
                    $input = new \WxPayOrderQuery();
                    $input->SetOut_trade_no($out_trade_no);

                    $data=\WxPayApi::orderQuery($config,$input);


                   //                file_put_contents('ali.txt',json_encode($data));
 Cache::set($order_no,'');
 
                    if($data['return_code'] == 'SUCCESS' ){
                        if($data['result_code'] == 'SUCCESS'){
                            //查询成功,等待用户支付
                            if($data['trade_state'] == 'USERPAYING'){
                                to_json($code = 0,$message = '等待用户支付',$data =[]);
                            }
                            //支付成功
                            if($data['trade_state'] == 'SUCCESS'){
                                $order_model=db('order');
                                        $amount=$data['total_fee']/100;
                                        if($amount !=$order_info['money']){
                                                to_json($code = 0,$message = '支付金额错误',$data =[]);
                                        }

                                    $update['status'] = 1;
                                    $update['note'] = $data['transaction_id'];
                                    $update['pay_time'] = date('Y-m-d H:i:s', time());
                                    $update['update_time'] = time();
                                    $res1 = Db::name("recharge")->where("account = ".$order_info['order_no'])->update($update);
                                    $Member_che = Db::name("member")->where("uid =" .$order_info['uid'])->find();
                                    $ying['credit2'] = $Member_che['credit2']+$amount;

                                   file_put_contents('11.txt',json_encode($ying));
                                    $ying_che = Db::name("member")->where("uid =" . $order_info['uid'])->update($ying);
                                      $status2['uid'] =$order_info['uid'];
                                      $status2['type'] ='credit2';
                                      $status2['num'] =$amount;
                                      $status2['title'] ='会员充值';
                                      $status2['remark'] ="充值金额：{$amount}。";
                                      $status2['create_time'] =time();
                                      $status2['balance']=$ying['credit2'];

                                      file_put_contents('2222.txt',json_encode($status2));
                                    $ass = Db::name("credit_record")->insert($status2);


                                    $order_data=[
                                        'status'=>2,
                                        'trade_no'=>$data['transaction_id'],
                                        'buyer_logon_id'=>$data['openid'],
                                        'send_pay_date'=>$data['time_end'],
                                        'query_time'=>time(),
                                    ];
                                    $rst=$order_model->where('order_no',$order_no)->update($order_data);

                                    if($rst){
                                         to_json($code = 1,$message = '微信支付成功',$data =[]);
                                    }else{
                                          to_json($code = 0,$message = '更新用户信息失败，请联系客服',$data =[]);
                                    }

                            }

                        }else{

                             to_json($code = 0,$message = '参数错误',$data =[]);
                        }
                    }else{
                        to_json($code = 0,$message = '查询失败',$data =[]);

                    }

            }



        //生成订单号
        public  function create_order_no(){
                //生成24位唯一订单号码，格式：YYYY-MMDD-HHII-SS-NNNN,NNNN-CC，其中：YYYY=年份，MM=月份，DD=日期，HH=24格式小时，II=分，SS=秒，NNNNNNNN=随机数，CC=检查码
                 @date_default_timezone_set("PRC");
                 //订购日期
                    $order_date = date('Y-m-d');
                    //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
                    $order_id_main = date('YmdHis') . rand(10000000,99999999);
                    //订单号码主体长度
                    $order_id_len = strlen($order_id_main);
                    $order_id_sum = 0;
                    for($i=0; $i<$order_id_len; $i++){
                                    $order_id_sum += (int)(substr($order_id_main,$i,1));
                    }
                    //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
                    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
                    return $order_id;
        }


//对象转数组
    public function object_array($array) {
        if(is_object($array)) {
                $array = (array)$array;
        }
        if(is_array($array)) {
                foreach($array as $key=>$value) {
                        $array[$key] = $this->object_array($value);
                }
        }
        return $array;
}

    public function fail(){

        $order_no=request()->param('order_no');
        if(!$order_no){
                message('参数错误','reload','error');
        }

         $member = $this->checkLogin();
         
        $update['status'] = 2;

        $res1 = Db::name("recharge")->where("account = ". $order_no)->update($update);
         
         
        $where=[
            'order_no'=>$order_no,
            'uid'=>$member['uid']
        ];

        $rst=db('order')->where($where)->setField('status',3);
        if($rst){
               message('取消成功','reload','success');
        }else{
            message('取消失败','reload','error');
        }

    }
    
    
}